package com.haidong.web;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;

/**
 * 响应字节数据
 */
@WebServlet("/resp4")
public class ResponseDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("text/html;charset=utf-8");
        try(
                FileInputStream fis = new FileInputStream("C:\\Users\\16877\\Desktop\\照片\\team.jpg");
                BufferedInputStream bis = new BufferedInputStream(fis);
                ) {
            ServletOutputStream sos = resp.getOutputStream();

            //完成流字节的复制
//            byte[] buffer = new byte[1024 * 8];
//            int len = 0;
//            while((len = bis.read(buffer))!=-1){
//                sos.write(buffer,0,len);
//            }

            // 使用工具类commons-io一行代码搞定
            IOUtils.copy(bis,sos);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
